/**
 * 剑指 Offer 29. 顺时针打印矩阵
 * https://leetcode-cn.com/problems/shun-shi-zhen-da-yin-ju-zhen-lcof/
 */
const { displayBaseArray } = require('../../libs/public');

/**
 * @param {number[][]} matrix
 * @return {number[]}
 */
function spiralOrder(matrix) {
  const { length: m } = matrix;
  if (!m) {
    return [];
  }
  const { length: n } = matrix[0];
  if (!n) {
    return [];
  }
  let begin = 0;
  const end = Math.ceil(Math.min(m, n) / 2) - 1;
  const result = new Array(m * n).fill(0);
  let cur = 0;
  for (; begin <= end; begin += 1) {
    const endH = n - begin - 1;
    const endV = m - begin - 1;
    if (begin === endH) {
      for (let i = begin; i <= endV; i += 1, cur += 1) {
        result[cur] = matrix[i][begin];
      }
      continue;
    }
    if (begin === endV) {
      for (let i = begin; i <= endH; i += 1, cur += 1) {
        result[cur] = matrix[begin][i];
      }
      continue;
    }
    for (let i = begin; i < endH; i += 1, cur += 1) {
      result[cur] = matrix[begin][i];
    }
    for (let i = begin; i < endV; i += 1, cur += 1) {
      result[cur] = matrix[i][endH];
    }
    for (let i = endH; i > begin; i -= 1, cur += 1) {
      result[cur] = matrix[endV][i];
    }
    for (let i = endV; i > begin; i -= 1, cur += 1) {
      result[cur] = matrix[i][begin];
    }
  }
  return result;
}

console.log(displayBaseArray(spiralOrder([
  [1, 2, 3],
  [4, 5, 6],
  [7, 8, 9],
])) === '[1,2,3,6,9,8,7,4,5]');
console.log(displayBaseArray(spiralOrder([
  [1, 2, 3, 4],
  [5, 6, 7, 8],
  [9, 10, 11, 12],
])) === '[1,2,3,4,8,12,11,10,9,5,6,7]');
console.log(displayBaseArray(spiralOrder([
  [1],
])) === '[1]');
console.log(displayBaseArray(spiralOrder([
  [1, 2],
])) === '[1,2]');
console.log(displayBaseArray(spiralOrder([
  [1],
  [2],
])) === '[1,2]');
console.log(displayBaseArray(spiralOrder([
  [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
  [11, 12, 13, 14, 15, 16, 17, 18, 19, 20],
])) === '[1,2,3,4,5,6,7,8,9,10,20,19,18,17,16,15,14,13,12,11]');
